﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.IO;

namespace Ewell.Interface.Common.Utils
{
    public class JsonConfig
    {
        /// <summary>
        /// 读取配置文件
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string ReadConfig(string fileName, string key)
        {
            string strPath = System.Environment.CurrentDirectory + "\\config";
            LogHelper.Debug(strPath);
            string value = string.Empty;
            if (File.Exists(strPath + $"\\{fileName}.json"))
            {
                using (System.IO.StreamReader file = System.IO.File.OpenText(strPath + $"\\{fileName}.json"))
                {

                    using (JsonTextReader reader = new JsonTextReader(file))
                    {
                        JObject o = (JObject)JToken.ReadFrom(reader);
                        value = o[key]?.ToString();
                    }

                }
            }
            return value;
        }
        public static string ReadFullFileConfig(string fileName, string key)
        {
            LogHelper.Debug($"{fileName} {key}");
            string value = string.Empty;
            if (File.Exists(fileName))
            {
                using (System.IO.StreamReader file = System.IO.File.OpenText(fileName))
                {

                    using (JsonTextReader reader = new JsonTextReader(file))
                    {
                        JObject o = (JObject)JToken.ReadFrom(reader);
                        value = o[key]?.ToString();
                    }

                }
            }
            return value;
        }
        /// <summary>
        /// 初始化配置到类
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static T IniConfig<T>(string fileName) where T : new()
        {
            T t = new T();
            string strPath = System.Environment.CurrentDirectory + "\\config";
            string value = string.Empty;
            if (File.Exists(strPath + $"\\{fileName}.json"))
            {
                using (System.IO.StreamReader file = System.IO.File.OpenText(strPath + $"\\{fileName}.json"))
                {
                    if (File.Exists(strPath + $"\\{fileName}.json"))
                    {
                        using (JsonTextReader reader = new JsonTextReader(file))
                        {
                            t = JObject.Load(reader).ToObject<T>();
                        }
                    }
                }
            }
            return t;
        }
    }
}
